#include "dialog.h"
#include "ui_dialog.h"
#include <QMessageBox>
#include <QPainter>
#include <QDateTime>
//构造函数
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),// 调用基类 QDialog 的构造函数
    ui(new Ui::Dialog)// 初始化 UI 对象（由 Qt Designer 生成）
{
    ui->setupUi(this);// 加载 UI 布局
    setWindowFlags(Qt::WindowStaysOnTopHint);// 设置窗口置顶
    ui->stackedWidget->setCurrentIndex(0);// 默认显示 stackedWidget 的第 0 页

    // 连接按钮
    // 连接 TCP 服务器的按钮
    connect(ui->pushButtonConn, &QPushButton::clicked, this, &Dialog::btnConnClickedSlot);

    client = new QTcpSocket(this);// 创建 TCP 客户端

    // 连接状态监测
    // connected 信号：当客户端成功连接服务器时，调用 connectedSlot。
    // disconnected 信号：当客户端断开连接时，调用 disconnectedSlot。
    connect(client, &QTcpSocket::connected, this, &Dialog::connectedSlot);//连接成功触发
    connect(client, &QTcpSocket::disconnected, this, &Dialog::disconnectedSlot);//断开连接触发

    // 注册和登录按钮
    connect(ui->pushButtonRegister, &QPushButton::clicked, this, &Dialog::registerSlot);
    connect(ui->pushButtonLogin, &QPushButton::clicked, this, &Dialog::loginSlot);

    // 发送消息按钮
    connect(ui->pushButtonSend, &QPushButton::clicked, this, &Dialog::btnSendClickedSlot);
    // 连接查询按钮
    connect(ui->btnQuery, &QPushButton::clicked,this, &Dialog::executeQuery);
    // 界面切换按钮
    connect(ui->pushButtonEnd, &QPushButton::clicked, this, &Dialog::btnChagepageSlot);
    connect(ui->pushButtonHis, &QPushButton::clicked, this, &Dialog::btnChagepageSlot2);
    connect(ui->pushButtonEHis, &QPushButton::clicked, this, &Dialog::btnChagepageSlot3);
}
//析构函数
Dialog::~Dialog()
{
    if(client->isOpen())// 检查 TCP 连接是否仍处于打开状态
        client->close();// 如果连接未关闭，则主动关闭
    delete ui;// 释放 UI 对象
}
//绘画函数
void Dialog::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);// 标记未使用的参数，避免编译器警告
    // 1. 绘制背景图片
    QPainter painter(this);
    QPixmap pic(":/new/prefix1/bd.jpg");
    painter.drawPixmap(0, 0, this->width(), this->height(), pic);
    // 2. 设置控件透明背景
    ui->lineEditPassword->setStyleSheet("QLineEdit { background-color: transparent; }");
    ui->lineEdit_Id->setStyleSheet("QLineEdit { background-color: transparent; }");
    ui->lineEdit_IP->setStyleSheet("QLineEdit { background-color: transparent; }");
    ui->textBrowser->setStyleSheet("QTextBrowser { background-color: transparent; }");
    ui->textBrowserHis->setStyleSheet("QTextBrowser { background-color: transparent; }");
}

//连接按钮发出连接
void Dialog::btnConnClickedSlot()
{
    QString ip = ui->lineEdit_IP->text();
    if(ip.isEmpty())
    {
        QMessageBox::warning(this, "提示", "请输入IP地址!");
        return;
    }

    quint16 port = ui->spinBox_2->value();
    if(port == 0)
    {
        QMessageBox::warning(this, "提示", "请输入端口号!");
        return;
    }

    client->connectToHost(ip, port);
}
//成功连接
void Dialog::connectedSlot()
{
    ui->pushButtonConn->setEnabled(false);// 禁用连接按钮
    ui->pushButtonConn->setText("已连接");// 更新按钮文本
    connect(client, &QTcpSocket::readyRead, this, &Dialog::readyReadSlot);// 绑定数据接收信号
    client->waitForReadyRead(1000);// 等待数据到达（超时 1 秒）
}
//断开连接
void Dialog::disconnectedSlot()
{
    ui->pushButtonConn->setEnabled(true);// 恢复连接按钮可用
    ui->pushButtonConn->setText("连接");// 重置按钮文本
    QMessageBox::warning(this, "提示", "连接已断开！");// 弹出断开提示
}

//数据接收
void Dialog::readyReadSlot()
{
    while(client->canReadLine()) { // 检查是否有完整的一行数据
        QString line = QString::fromUtf8(client->readLine()).trimmed();// 读取一行并去除首尾空白
        QStringList parts = line.split("|"); // 按冒号分割协议字段
        if(parts.isEmpty()) continue;// 跳过空行
        if(parts[0] != "REGISTER"&&parts[0] != "LOGIN"&&parts[0] != "MESSAGE"&&parts[0] != "QUERY_RESULT"&&parts[0] != "ERROR"&&parts[0] != "QUERY_ERROR"){
            QString message = parts[0];
            ui->textBrowser->append(message);
        }

        // 根据协议类型处理不同逻辑
        if(parts[0] == "REGISTER") {
            if(parts.size() >= 2 && parts[1] == "SUCCESS") {
                QMessageBox::information(this, "成功", "注册成功！");
            } else {
                QString errorMsg = parts.size() >= 3 ? parts[2] : "未知错误";
                QMessageBox::warning(this, "注册失败", errorMsg);
            }
        }
        else if(parts[0] == "LOGIN") {
            if(parts.size() >= 2 && parts[1] == "SUCCESS") {
                QMessageBox::information(this, "成功", "登录成功！");
                ui->stackedWidget->setCurrentIndex(1);// 切换到登录后的界面
            } else {
                QMessageBox::warning(this, "登录失败", "用户名或密码错误");
            }
        }
        else if(parts[0] == "MESSAGE") {
            if(parts.size() >= 4) {
                QString timestamp = parts[1];// 时间戳
                QString nickname = parts[2];// 昵称
                QString message = parts.mid(3).join("|");// 合并剩余字段为消息内容
                // 将消息按格式显示在 textBrowser 中
                QString displayMsg = timestamp + "\n" + nickname + ": " + message;
                ui->textBrowser->append(displayMsg);
            }
        }
        else if(parts[0] == "QUERY_RESULT") {
            if(parts.size() >= 5) {
                // QString type = parts[1]; // 查询类型
                QString timestamp = parts[2]; // 时间戳
                QString nickname = parts[3]; // 昵称
                QString message = parts.mid(4).join("|");// 消息内容

                QString displayMsg =timestamp+"\n"+ nickname+":"+message;
                ui->textBrowserHis->append(displayMsg);
            }
            else if(parts.size() >= 2 && parts[1] == "END") {
                QMessageBox::information(this, "提示", "查询结束");
            }
        }
        else if(parts[0] == "ERROR" || parts[0] == "QUERY_ERROR") {
            QString errorMsg = parts.size() >= 2 ? parts[1] : "未知错误";
            QMessageBox::warning(this, "错误", errorMsg);
        }
    }
}

//注册
void Dialog::registerSlot()
{
    // 处理用户注册逻辑，包括输入验证、密码哈希处理和向服务器发送注册请求
    if(!client->isOpen()) {
        QMessageBox::warning(this, "提示", "请先连接服务器！");
        return;
    }
    // 验证用户名输入
    QString username = ui->lineEdit_Id->text();
    if(username.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入用户名！");
        return;
    }
    // 验证密码输入
    QString password = ui->lineEditPassword->text();
    if(password.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入密码！");
        return;
    }
    // 密码哈希处理
    QString hashedPassword = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256).toHex();

    // 构造注册命令并发送
    QString command = QString("REGISTER|%1|%2\n").arg(username, hashedPassword);
    client->write(command.toUtf8());
}

//登录
void Dialog::loginSlot()
{
    // 处理用户登录逻辑，包括输入验证、密码哈希处理和向服务器发送登录请求。
    if(!client->isOpen()) {
        QMessageBox::warning(this, "提示", "请先连接服务器！");
        return;
    }

    QString username = ui->lineEdit_Id->text();
    if(username.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入用户名！");
        return;
    }

    QString password = ui->lineEditPassword->text();
    if(password.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入密码！");
        return;
    }

    QString hashedPassword = QCryptographicHash::hash(password.toUtf8(),
                                                      QCryptographicHash::Sha256).toHex();

    QString command = QString("LOGIN|%1|%2\n").arg(username, hashedPassword);
    client->write(command.toUtf8());
}

//发送消息
void Dialog::btnSendClickedSlot()
{
    // 检查客户端连接状态
    if(!client->isOpen()) {
        QMessageBox::warning(this, "提示", "请先连接服务器！");
        return;
    }

    // 验证昵称输入
    QString nickname = ui->lineEditUser->text();
    if(nickname.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入昵称！");
        return;
    }

    // 验证消息内容
    QString message = ui->plainTextEdit->toPlainText();
    if(message.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入消息内容！");
        return;
    }
    // 检查消息长度
    if(message.size() > 128) {
        QMessageBox::warning(this, "提示", "消息内容过长！");
        return;
    }

    // 构造消息命令并发送
    QString command = QString("MESSAGE|%1|%2\n").arg(nickname, message);
    client->write(command.toUtf8());

    // 本地显示消息
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString displayMsg = timestamp + "\n" + nickname + "(本机): " + message;
    ui->textBrowser->append(displayMsg);
    // 清空输入框
    ui->plainTextEdit->clear();
}

//查询
void Dialog::executeQuery()
{
    //清空结果
    ui->textBrowserHis->clear();
    QString text = ui->comboBox->currentText().trimmed();

    if (!client || !client->isWritable()) {
        QMessageBox::warning(this, "错误", "客户端未连接！");
        return;
    }

    QString queryText = ui->plainTextEditHis->toPlainText().trimmed();
    if (text == "查询所有聊天记录") {
        client->write("QUERY_ALL\n");
    }
    else
    {
        if(queryText.isEmpty() && text != "查询所有聊天记录")
        {
            QMessageBox::warning(this, "提示", "请输入查询内容！");
            return;
        }

        if (text == "按时间查询") {
            client->write(QString("QUERY_TIME|%1\n").arg(queryText).toUtf8());
        }
        else if (text == "按昵称查询") {
            client->write(QString("QUERY_NICKNAME|%1\n").arg(queryText).toUtf8());
        }
        else if (text == "按消息内容查询") {
            client->write(QString("QUERY_MSG|%1\n").arg(queryText).toUtf8());
        }

    }
}

//切换页面
void Dialog::btnChagepageSlot()
{
    ui->stackedWidget->setCurrentIndex(0);
}
void Dialog::btnChagepageSlot2()
{
    ui->stackedWidget->setCurrentIndex(2);
}
void Dialog::btnChagepageSlot3()
{
    ui->stackedWidget->setCurrentIndex(1);
}
